package algorithm;

import java.util.*;

/**
 * 给定一个二叉树，返回它的 前序 遍历
 */
public class T00144 {
    public static void main(String[] args) {
        Integer[] arr = new Integer[]{1,2,3,4,null,6,7,null,5,null,null,null,8};
        TreeNode root = build(arr);
        System.out.println(new Solution().preorderTraversal(root));
    }

    static TreeNode build(Integer[] arr) {
        if(arr == null || arr.length == 0)
            return null;
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(arr[0]);
        queue.offer(root);
        for (int i = 1; i < arr.length; i++) {
            TreeNode t = queue.poll();
            if(t != null) {
                // 构建左节点
                if(arr[i] != null) {
                    TreeNode left = new TreeNode(arr[i]);
                    queue.offer(left);
                    t.left = left;
                }
                // 构建右节点
                if(i + 1 < arr.length && arr[++ i] != null) {
                    TreeNode right = new TreeNode(arr[i]);
                    queue.offer(right);
                    t.right = right;
                }
            }
        }
        return root;
    }

static class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null)
            return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        boolean flag = false;
        for(;;) {
            if(cur == null)
                break;
            if(flag) { // 遍历右
                if(cur.right != null) { // 存在右节点，到右节点
                    cur = cur.right;
                    flag = false;
                } else {
                    if(stack.isEmpty())
                        break;
                    cur = stack.pop();
                }
            } else { // 遍历左
                list.add(cur.val);
                if(cur.left != null) { // 存在左节点，到左节点，父节点入栈
                    stack.push(cur);
                    cur = cur.left;
                } else {
                    flag = true;
                }
            }
        }
        return list;
    }
}

    private static class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode() {}
         TreeNode(int val) { this.val = val; }
         TreeNode(int val, TreeNode left, TreeNode right) {
             this.val = val;
             this.left = left;
             this.right = right;
         }
    }
}